#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char const* argv[])
{
    int fd[3], i, val;

    fd[0] = open("file", O_RDONLY);
    if (fd[0] < 0)
    {
        perror("open error\n");
        exit(0);
    }

    fd[1] = dup(fd[0]);

    fd[2] = open("file", O_RDONLY);
    if (fd[2] < 0)
    {
        perror("open error\n");
        exit(0);
    }

    printf("\n");
    for (i = 0; i < 3; i++) {
        printf("before change, fd[%d], FD_CLOEXEC is %d\n",
            i, fcntl(fd[i], F_GETFD, 0));
    }

    printf("\n");
    for (i = 0; i < 3; i++) {
        val = fcntl(fd[i], F_GETFL, 0);
        printf("before change, fd[%d], O_APPEND is %d\n",
            i, (val & O_APPEND));
    }

    fcntl(fd[0], F_SETFD, 1);
    val = fcntl(fd[0], F_GETFL, 0);
    val |= O_APPEND;
    fcntl(fd[0], F_SETFL, val);

    printf("\n");
    for (i = 0; i < 3; i++) {
        printf("after change, fd[%d], FD_CLOEXEC is %d\n",
            i, fcntl(fd[i], F_GETFD, 0));
    }

    printf("\n");
    for (i = 0; i < 3; i++) {
        val = fcntl(fd[i], F_GETFL, 0);
        printf("after change, fd[%d], O_APPEND is %d\n",
            i, (val & O_APPEND));
    }

    return 0;
}
